package com.example.gateway.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.data.redis.connection.ReactiveRedisConnection;
import org.springframework.data.redis.core.ReactiveStringRedisTemplate;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

@Component
public class RedisTestRunner implements CommandLineRunner {

    @Autowired
    private ReactiveStringRedisTemplate redisTemplate;

    @Override
    public void run(String... args) throws Exception {
        // 先尝试 PING Redis 以测试连接
        ReactiveRedisConnection connection = redisTemplate.getConnectionFactory().getReactiveConnection();

        connection.ping()
                .flatMap(pong -> {
                    System.out.println("✅ Redis 连接成功，PING 响应: " + pong);

                    // 写入测试 key
                    String testKey = "test:connection";
                    String testValue = "hello redis";
                    return redisTemplate.opsForValue().set(testKey, testValue)
                            .flatMap(setResult -> {
                                if (setResult) {
                                    System.out.println("✅ Redis 写入成功，开始读取...");
                                    return redisTemplate.opsForValue().get(testKey);
                                } else {
                                    System.err.println("❌ Redis 写入失败！");
                                    return Mono.empty();
                                }
                            });
                })
                .subscribe(value -> {
                    System.out.println("✅ Redis 读取值: " + value);
                }, error -> {
                    System.err.println("❌ Redis 操作异常: " + error.getMessage());
                });
    }
}
